#!/usr/bin/python

import os
import sys
import datetime

from movie.vote.models import Movie
import urllib
import re
import imdb

def FindReviewUrl(regex, html):
  c = re.compile(regex)
  found = []
  for line in html:
    found.extend(c.findall(line))
  return found

def UpdateMovieReviews(days_back=0):
  imdb_access = imdb.IMDb()
  if not days_back:
    movies = Movie.objects.all()
  else:
    cutoff = datetime.datetime.now() - datetime.timedelta(days_back)
    movies = Movie.objects.filter(date_added__gt=cutoff)
  for movie in movies:
    if not movie.imdb_url or (movie.metacritic_url and movie.rotten_url):
      continue
    url = movie.imdb_url + 'externalreviews'
    html = urllib.urlopen(url).readlines()

    if not movie.metacritic_url:
      review_urls = FindReviewUrl(r'(http://www.metacritic.com/.*?)"', html)
      if review_urls:
        print '%s %s' % (movie, review_urls[0])
        movie.metacritic_url = review_urls[0]
        movie.save()
    if not movie.rotten_url:
      review_urls = FindReviewUrl(r'(http://www.rottentomatoes.com/.*?)"', html)
      # If there is link of format 'rottentomatoes.com/m/', always use it
      candidates = [x for x in review_urls if 'rottentomatoes.com/m/' in x]
      if candidates:
        review_urls = candidates
      for review in review_urls:
        if 'author' in review:
          continue
        if '/tools/' in review:
          continue
        print '%s %s' % (movie, review)
        movie.rotten_url = review
        movie.save()
        break


if __name__ == '__main__':
  days_back = 5
  if len(sys.argv) > 1:
    days_back = int(sys.argv[1])
  UpdateMovieReviews(days_back)
